package com.gonsin.easycount.plugin.impl;

import com.gonsin.easycount.exception.EasyCountException;
import com.gonsin.easycount.plugin.OuterNotifyExecutor;
import com.gonsin.easycount.task.NotifyExecutorTask;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.concurrent.atomic.AtomicBoolean;

public class LocalExecutor implements OuterNotifyExecutor {

    private SchedulerFactory schedulerFactory;

    private AtomicBoolean started = new AtomicBoolean(false);

    public LocalExecutor() {
        this.schedulerFactory = new StdSchedulerFactory();
    }

    /**
     * 开启定时器
     */
    @Override
    public void start(){
        if(started.getAndSet(true)){
            throw new EasyCountException("LocalExecutor.start() 只能被执行一次");
        }
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            JobDetail jobDetail = JobBuilder.newJob(NotifyExecutorTask.class).withIdentity("NotifyExecutorTask")// 任务名称和组构成任务key
                    .build();
            // 定义调度触发规则
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("NotifyExecutorTask")// 触发器key
                    .startNow()
                    .withSchedule(CronScheduleBuilder.cronSchedule("*/1 * * * * ?"))
                    .build();

            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new EasyCountException(e.getMessage());
        }
    }

}
